package com.comecrd.service.impl;

import com.comecrd.model.Comment;
import com.comecrd.model.dto.CommentDTO;
import com.comecrd.repository.CommentMapper;
import com.comecrd.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    
    @Autowired
    private CommentMapper commentMapper;
    
    @Override
    @Transactional
    public Comment save(Comment comment) {
        commentMapper.insert(comment);
        return comment;
    }
    
    @Override
    public List<CommentDTO> findByCheckInId(Long checkInId, int page, int size) {
        int offset = (page - 1) * size;
        return commentMapper.selectByCheckInId(checkInId, offset, size);
    }
    
    @Override
    public int countByCheckInId(Long checkInId) {
        Integer count = commentMapper.countByCheckInId(checkInId);
        return count != null ? count : 0;
    }
    
    @Override
    @Transactional
    public void deleteById(Long commentId, Long userId) {
        commentMapper.deleteByIdAndUserId(commentId, userId);
    }
    
    @Override
    public CommentDTO convertToDTO(Comment comment) {
        // 由于MyBatis已经在SQL中直接返回了DTO对象，这个方法可能不再需要
        // 但为了保持接口兼容性，这里简单实现
        if (comment == null) {
            return null;
        }
        
        CommentDTO dto = new CommentDTO();
        dto.setId(comment.getId());
        dto.setCheckInId(comment.getCheckInId());
        dto.setContent(comment.getContent());
        dto.setCreatedAt(comment.getCreatedAt());
        
        return dto;
    }
    
    @Override
    public List<CommentDTO> convertToDTOList(List<Comment> comments) {
        return comments.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
}